package com.example.springboot_blog.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot_blog.domain.Article;
import com.example.springboot_blog.domain.Comment;
import com.example.springboot_blog.service.Impl.ArticleServiceImpl;
import com.example.springboot_blog.service.Impl.CommentServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

/**
 * @author 白草风归
 */
@Controller

public class ClientController {
    @Autowired
    private ArticleServiceImpl articleService;
    @Autowired
    private CommentServiceImpl commentService;

    /**
     * @Param:a
     *@Retrrn:a
     * 访问主页时转到分页的第一页
     */

    @GetMapping("/")
    public String index(Model model){
        return page(1, model);
    }
    /**
     * @Param:a
     *@Retrrn:a
     * 分页显示文章
     */
    @GetMapping("/page/{page}")
    public String page(@PathVariable("page") int page, Model model){
        Page<Article> articles = articleService.getPage(page, 5);
        model.addAttribute("page", page);
        model.addAttribute("totalPage", articles.getPages());
        model.addAttribute("articles", articles.getRecords());
        return "client/index";
    }

    /**
     * @Param:a
     * @Rerrn:a
     * 文章详情页
     */
    @GetMapping("/article/{id}")
    public String article(@PathVariable("id") int id, Model model){
        Article article = articleService.getById(id);
        List<Comment> comments = commentService.selectCommentList(id);
        model.addAttribute("article", article);
        model.addAttribute("comments",comments);
        return "client/article";
    }
    /**
     * @Param:a
     * @Rerrn:a
     * 发表评论
     */
    @PostMapping("/article/{id}/comment")
    public String comment(@PathVariable("id") int id, @RequestParam("username") String username, @RequestParam("body")String body){
        commentService.addComment(id, username, body);
        return "redirect:/article/"+id;
    }
}
